import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  Divider,
  Popconfirm,
  Select,
} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';
import {ruleP, nameMaxLength,remarkMaxLength} from '@/utils/rule'
const { TextArea } = Input;
const FormItem = Form.Item;
const isDefault = ['内置', '自定义'];
const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑字典类型':'新增字典类型'}
      visible={modalVisible}
      onOk={() => okHandle()}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="类型编码">
        {form.getFieldDecorator('dicTypeCode', {
          rules: [{ required: true, whitespace:true, message: '字典编码不能为空'},
          {pattern:new RegExp(ruleP(1)[0],'g'), message:ruleP(1)[1]},{max:60,message:"字符长度不能60"}],
          initialValue: text&&text.dataDictTypeCode || ''
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="类型名称">
        {form.getFieldDecorator('dicTypeName', {
          rules: [{ required: true, whitespace:true, message: '类型名称不能为空'},{max:nameMaxLength()[0], message:nameMaxLength()[1]}], initialValue: text&&text.dataDictTypeName || ''
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} label="备注">
        {form.getFieldDecorator('remark', {rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],initialValue: text&&text.remark || ''
        })(<TextArea placeholder="请输入" rows={2} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ dicType, loading }) => ({
  dicType,
  loading: loading.models.dicType,
}))

@Form.create()
class dicTypeList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    formValues: {},
    expandForm: false,
    selectedRows: [],
    text: {}
  };

  columns = [
    {
      title: '类型名称',
      dataIndex: 'dataDictTypeName',
    },
    {
      title: '类型编码',
      dataIndex: 'dataDictTypeCode',
    },
    {
      title: '类型',
      dataIndex: 'isDefault',
      render(val) {
        return isDefault[val];
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width:"40%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          {text.isDefault==1?(
            <Fragment>
              <Divider type="vertical" />
              <a onClick={() => this.deleteData(text.id)}>删除</a>
            </Fragment>
          ):null}
        </Fragment>
      ),
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  // 删除方法
  handleDeleteData(id) {
    const { dispatch } = this.props;
    const {formValues} = this.state;
    const values = {
     id
    };

    dispatch({
      type: 'dicType/remove',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      dataDictTypeName: data&&data.dicTypeName||'',
      dataDictTypeCode: data&&data.dicTypeCode||'',
      isDefault: data&&data.isDefault||'',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'dicType/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);
    });
  };

// 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      id: text.id,
      dataDictTypeCode: fields.dicTypeCode,
      dataDictTypeName:fields.dicTypeName,
      remark: fields.remark,
    }
    dispatch({
      type: 'dicType/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
        dataDictTypeCode: fields.dicTypeCode,
        dataDictTypeName:fields.dicTypeName,
        remark: fields.remark,
    }
    dispatch({
      type: 'dicType/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="类型名称">
              {getFieldDecorator('dicTypeName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="类型">
              {getFieldDecorator('isDefault')(
                <Select placeholder="请选择">
                  <Option value="">全部</Option>
                  <Option value="0">内置</Option>
                  <Option value="1">自定义</Option>                 
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  };

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  };

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  render() {
    const {
      dicType: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, text } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };

    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text}/>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

export default dicTypeList;
